package com.peng.sell.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Slf4j
@ServerEndpoint("/webSocket")
public class WebSocket {
    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketSet.add(this);
        log.info("【webSocket消息】有一个新连接。。现在总连接数：{}",webSocketSet.size());
    }

    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        log.info("【webSocket消息】有一个断开连接了。。现在总连接数：{}",webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message){
        log.info("【webSocket消息】来自客户端的消息：{}",message);
    }

    public void sendMessage(String message){
        for (WebSocket webSocket : webSocketSet){
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("【webSocket消息】发送消息出现错误：{}",e);
            }
        }
    }

    @OnError
    public void onError(Throwable throwable){
        log.warn("【webSocket消息】webSocket消息发生错误了:{}",throwable);
    }

}
